#!/usr/bin/env php
<?php
/**
 * Yii Application Initialization env
 *
 * env-init --env=dev --debug=1
 */

$params = getParams();

$root = str_replace('\\', '/', __DIR__);

echo "Yii 环境初始化工具 v1.0" . PHP_EOL . PHP_EOL;

//环境配置
$envConfig = require_once ($root . '/environments/env.conf.php');

//拥有配置文件的环境列表
$haveConfigEnvList = getEnvDirList($root . '/environments');
$selectEnv = array_keys($envConfig['envList']);

$envName = null;
//输入环境监测
if (empty($params['env']) || $params['env'] === true) {
    echo "请选择你要初始化的环境?脚本会自动生成对应的env.php文件" . PHP_EOL . PHP_EOL;

    foreach ($selectEnv as $i => $name) {
        echo "  [{$i}] " . $name . ' ('.$envConfig['envList'][$name]['desc'].')' .  PHP_EOL;
    }
    echo "  你可以选择输入 [0-" . (count($selectEnv) - 1) . ', 或 回车 退出] ' ;
    $answer = trim(fgets(STDIN));

    if (!ctype_digit($answer) || !in_array($answer, range(0, count($selectEnv) - 1))) {
        echo PHP_EOL . "  选择错误 退出初始化脚本." . PHP_EOL;
        exit(0);
    }
    $envName = $selectEnv[$answer];
} else {
    $envName = $params['env'];
}

//配置文件环境检测
if (!in_array($envName, $selectEnv, true)) {
    $envsList = implode(', ', $selectEnv);
    echo  "  `$envName` 环境名不在配置文件 env.conf.php 中  请检查文件中的变量: $envsList " . PHP_EOL;
    exit(2);
}
//配置文件夹检测
if (!in_array($envName, $haveConfigEnvList, true)) {
    $envsList = implode(', ', $haveConfigEnvList);
    echo " `{$envName}` 环境名或环境对应的配置文件夹不存在 . 请检查该路径下是否存在对应环境名的配置文件夹: " . $root . '/environments/' . PHP_EOL;
    exit(2);
}

//复制对应环境下的yii文件到项目根目录
exec('cp '. $root.'/environments/'.$envName.'/yii'.' '.$root.'/yii');

//设置文件权限
echo "  开始初始化 ..." . PHP_EOL;

echo "  --设置读写权限setWritable list" . PHP_EOL;
setWritable($root,$envConfig['setWritable']);

echo "  --设置可执行权限setExecutable list" . PHP_EOL;
setExecutable($root,$envConfig['setExecutable']);

//生成配置文件
$debug = isset($params['debug']) && intval($params['debug']) ? 'true' : ($envName != 'prod' ? 'true' : 'false');

 $envPhpContent = <<<env
 <?php
    defined('YII_DEBUG') or define('YII_DEBUG', {$debug});
    defined('YII_ENV') or define('YII_ENV', '{$envName}');
    
env;

 //写入环境文件
file_put_contents($root . '/env.php',$envPhpContent);


echo "初始化完成." . PHP_EOL;



/**
 * 获取制定路径文件夹
 * getEnvDirList
 * @time 2019/6/25 23:06
 * @author ityong
 * @param $root
 * @return array
 */
function getEnvDirList ($root)
{
    $envList = [];
    $handle = opendir($root);
    while (($path = readdir($handle)) !== false) {
        if ($path === '.git' || $path === '.svn' || $path === '.' || $path === '..') {
            continue;
        }
        if (!is_dir($root . "/" . $path)) continue;

        $envList[] = $path;
    }
    closedir($handle);
    return $envList;

}

/**
 * 获取文件列表
 * getFileList
 * @time 2019/6/25 23:07
 * @author ityong
 * @param $root
 * @param string $basePath
 * @return array
 */
function getFileList($root, $basePath = '')
{
    $files = [];
    $handle = opendir($root);
    while (($path = readdir($handle)) !== false) {
        if ($path === '.git' || $path === '.svn' || $path === '.' || $path === '..') {
            continue;
        }
        $fullPath = "$root/$path";
        $relativePath = $basePath === '' ? $path : "$basePath/$path";
        if (is_dir($fullPath)) {
            $files = array_merge($files, getFileList($fullPath, $relativePath));
        } else {
            $files[] = $relativePath;
        }
    }
    closedir($handle);
    return $files;
}


function getParams()
{
    $rawParams = [];
    if (isset($_SERVER['argv'])) {
        $rawParams = $_SERVER['argv'];
        array_shift($rawParams);
    }

    $params = [];
    foreach ($rawParams as $param) {
        if (preg_match('/^--([\w-]*\w)(=(.*))?$/', $param, $matches)) {
            $name = $matches[1];
            $params[$name] = isset($matches[3]) ? $matches[3] : true;
        } else {
            $params[] = $param;
        }
    }
    return $params;
}

function setWritable($root, $paths)
{
    foreach ($paths as $writable) {
        if (is_dir("$root/$writable")) {
            if (@chmod("$root/$writable", 0777)) {
                echo "      chmod 0777 $writable\n";
            } else {
                print_r("初始化脚本没有足够的权限去操作路径 $writable 的读写权限.");
            }
        } else {
            print_r("路径 $writable 不存在.");
        }
    }
}

function setExecutable($root, $paths)
{
    foreach ($paths as $executable) {
        if (file_exists("$root/$executable")) {
            if (@chmod("$root/$executable", 0755)) {
                echo "      chmod 0755 $executable\n";
            } else {
                print_r("初始化脚本没有足够的权限去操作路径 $executable 的执行权限.");
            }
        } else {
            print_r("路径  $executable 不存在.");
        }
    }
}

